﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Text;
using System.Linq;
using T.FAS.Runtime.Expression.SPI;
using Newtonsoft.Json.Linq;
using System.Net;
using System.IO;
using System.Configuration;
using T.FAS.Runtime.Expression.Entity;
using T.FAS.Runtime.Base.Entity;

namespace T.FAS.Runtime.Expression.Plugin
{
    public class ConfigCenterExecutor : DynamicObject, IDynamicActionAdapter
    {
        /// <summary>
        /// JS脚本动态调用Dynamic必备函数
        /// 脚本写法：ConfigCenter.();
        /// </summary>
        /// <param name="name">动态调用DynamicObject中的函数名称</param>
        /// <param name="args">参数信息，参数类型必须增加 params</param>
        /// <returns></returns>
        public dynamic DynamicInvoke(string name, params object[] args)
        {
            return ExecuteConfigCenter(name, args);
        }

        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out dynamic result)
        {
            result = DynamicInvoke(binder.Name, args);
            return true;
        }

        /// <summary>
        /// 执行获取配置中心值的逻辑
        /// </summary>
        /// <param name="funcName"></param>
        /// <param name="paramList"></param>
        /// <returns></returns>
        private dynamic ExecuteConfigCenter(string funcName, object[] paramList)
        {
            throw new FasException(ExprExceptionCode.NotSupported, "Unsupported ConfigCenter." + funcName);
        }

        /// <summary>
        /// 从配置中心获取配置项
        /// </summary>
        /// <param name="configKey"></param>
        /// <returns></returns>
        public string Get(string configKey)
        {
            string baseUriString = ConfigurationManager.AppSettings["ConfigCenter.Url"];
            if (string.IsNullOrEmpty(baseUriString) || string.IsNullOrEmpty(configKey))
            {
                return null;
            }
            Uri uri = new Uri(new Uri(baseUriString), "api/get?key=" + configKey);
            int Count = 3;
            while (Count >= 0)
            {
                try
                {
                    HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
                    request.ContentType = "application/json";
                    request.Method = "Get";
                    request.Timeout = 10000;
                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    {
                        using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
                        {
                            string responseMsg = streamReader.ReadToEnd();
                            JObject jt = JObject.Parse(responseMsg);
                            if (jt["result_code"].ToString() == "0")
                            {
                                return jt["result_content"].ToString();
                            }
                        }
                    }
                }
                catch
                {
                    Count--;
                    if (Count <= 0)
                    {
                        throw;
                    }
                    continue;
                }
                break;
            }
            return null;
        }
    }
}
